package com.neusoft.service.impl;

import com.neusoft.mapper.UserMapper;
import com.neusoft.mapper.OrdersMapper;
import com.neusoft.mapper.WalletMapper;
import com.neusoft.mapper.BusinessMapper;
import com.neusoft.po.Wallet;
import com.neusoft.po.WalletTransaction;
import com.neusoft.po.Business;
import com.neusoft.po.Orders;
import com.neusoft.service.WalletService;

import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Service;

//import java.time.LocalDateTime;
//import java.time.ZoneId;
import java.util.Date;
//import java.time.temporal.ChronoUnit;
import java.util.List;

/**
 * 钱包服务实现类，包含钱包业务逻辑处理，如充值、提现和转账。
 */
@Service
public class WalletServiceImpl implements WalletService {

    @Autowired
    private WalletMapper walletMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private BusinessMapper businessMapper;
    /*@Autowired
    private ThreadPoolTaskScheduler taskScheduler;

    public WalletServiceImpl() {
        this.taskScheduler = new ThreadPoolTaskScheduler();
        this.taskScheduler.setPoolSize(10);
        this.taskScheduler.initialize();
    }*/

    /**
     * 根据用户ID获取钱包信息。
     *
     * @param userId 用户ID
     * @return 钱包对象
     */
    @Override
    public Wallet getWalletByUserId(String userId) {
        return walletMapper.getWalletByUserId(userId);
    }

    /**
     * 充值功能，为用户钱包增加余额。如果用户没有钱包记录，则创建一个新的钱包。
     *
     * @param userId 用户ID
     * @param amount 充值金额
     * @return 操作是否成功
     */
    @Override
    public boolean recharge(String userId, Double amount) {
        Wallet wallet = walletMapper.getWalletByUserId(userId);
        if (wallet == null) {
            wallet = new Wallet(userId, 0.0, 0.0, 0.0, 0.0);
            walletMapper.createWallet(wallet);
        }

        Double rewardLowest = walletMapper.getRewardLowest();
        Double rewardAmount = walletMapper.getRewardAmount();

        int rewardCount = (int) (amount / rewardLowest);
        Double totalReward = rewardCount * rewardAmount;

        wallet.recharge(amount + totalReward);

        walletMapper.updateBalance(userId, wallet.getBalance());
        walletMapper.updateDebtAmount(userId, wallet.getDebtAmount());

        WalletTransaction transaction = new WalletTransaction();
        transaction.setTransaction(null, userId, null, userId, amount, "充值", new Date());
        walletMapper.addTransaction(transaction);
        return true;
    }

    /**
     * 提现功能，为用户钱包扣除余额。余额不足时抛出异常。
     *
     * @param userId 用户ID
     * @param amount 提现金额
     * @return 操作是否成功
     */
    @Override
    public boolean withdraw(String userId, Double amount) {
        Wallet wallet = walletMapper.getWalletByUserId(userId);
        if (wallet == null) return false;

        Double punishRate = walletMapper.getPunishRate();
        Double fee = amount * punishRate;
        Double totalAmount = amount + fee;

        boolean success = wallet.withdraw(totalAmount);
        if (!success) return false;

        walletMapper.updateBalance(userId, wallet.getBalance());

        WalletTransaction transaction = new WalletTransaction();
        transaction.setTransaction(null, userId, userId, null, amount, "提现", new Date());
        walletMapper.addTransaction(transaction);
        return true;
    }

    /**
     * 用户之间的转账功能，从一个用户的钱包转账到另一个用户的钱包。
     *
     * @param fromUserId 转出方用户ID
     * @param toUserId 接收方用户ID
     * @param amount 转账金额
     * @return 操作是否成功
     */
    @Override
    public boolean transfer(String fromUserId, String toUserId, Double amount) {
        Wallet fromWallet = walletMapper.getWalletByUserId(fromUserId);
        Wallet toWallet = walletMapper.getWalletByUserId(toUserId);
        final Wallet finalfromwallet = fromWallet;

        if (fromWallet == null || toWallet == null) {
            return false;
        }

        // 获取 fromUser 是否为 VIP 以及透支额度和余额信息
        boolean isVip = userMapper.getIsVip(fromUserId) == 1;
        Double overdraftLimit = walletMapper.getOverdraftLimit(fromUserId);
        Double currentBalance = fromWallet.getBalance();
        Double debtAmount = walletMapper.getDebtAmount(fromUserId);

        // 检查余额和透支额度是否足够
        if (currentBalance >= amount) {
            // 余额足够，直接扣款并冻结资金到toUser的冻结余额中
            walletMapper.updateBalance(fromUserId, currentBalance-amount);
            walletMapper.updateFrozenBalance(toUserId, amount);

        // 启动定时器，30秒后自动调用 confirmReceipt
        new java.util.Timer().schedule(new java.util.TimerTask() {
            @Override
            public void run() {
                confirmReceipt(toUserId, amount);
                System.out.println("自动确认收货成功：" + toUserId + " 金额：" + amount);
            }
        }, 30000);

        } else if (isVip && (currentBalance + overdraftLimit - debtAmount) >= amount) {
            // VIP 用户可以透支，并且透支额度足够
            Double overdraftNeeded = amount - currentBalance;
            walletMapper.updateBalance(fromUserId, 0.0);
            walletMapper.updateDebtAmount(fromUserId, debtAmount + overdraftNeeded);
            walletMapper.updateOverdraftLimit(fromUserId, overdraftLimit - overdraftNeeded);
            walletMapper.updateFrozenBalance(toUserId, amount);
            
            // 启动定时器，30秒后自动调用 confirmReceipt
            new java.util.Timer().schedule(new java.util.TimerTask() {
                @Override
                public void run() {
                    confirmReceipt(toUserId, amount);
                    System.out.println("自动确认收货成功：" + toUserId + " 金额：" + amount);
                }
            }, 30000);

            //透支额度逾期未还则增加利息
            new java.util.Timer().schedule(new java.util.TimerTask() {
                @Override
                public void run() {
                    if(finalfromwallet.getDebtAmount() > 0)
                    {
                        updatedebt(fromUserId);
                        System.out.println("利息++");
                    }
                    else {
                        System.out.println("利息清零");
                        this.cancel();
                    }
                }
            }, 0, 30*1000);
        } else {
            // 余额不足，且透支额度不够
            return false;
        }
        WalletTransaction fromtransaction = new WalletTransaction();
        fromtransaction.setTransaction(null, fromUserId, fromUserId, toUserId, amount, "转账", new Date());
        walletMapper.addTransaction(fromtransaction);
        WalletTransaction totransaction = new WalletTransaction();
        totransaction.setTransaction(null, toUserId, fromUserId, toUserId, amount, "转账", new Date());
        walletMapper.addTransaction(totransaction);

        return true;
    }

    @Override
    public boolean confirmReceipt(String toUserId, Double amount) {
        Wallet toWallet = walletMapper.getWalletByUserId(toUserId);
        if (toWallet == null) return false;

        walletMapper.updateFrozenBalance(toUserId, -amount);
        walletMapper.updateBalance(toUserId, toWallet.getBalance() + amount);
        return true;
    }

    @Override
    public boolean updatedebt(String fromUserId){
        Wallet fromWallet = walletMapper.getWalletByUserId(fromUserId);
        if(fromWallet != null){
            Double debt = fromWallet.getDebtAmount();
            walletMapper.updateDebtAmount(fromUserId, debt * 1.01);
        } 
        throw new IllegalArgumentException("钱包不存在！！！");
    }

    /**
     * 获取用户的所有交易记录。
     *
     * @param userId 用户ID
     * @return 交易记录列表
     */
    @Override
    public List<WalletTransaction> getTransactionsByUserId(String userId) {
        return walletMapper.getTransactionsByUserId(userId);
    }

    /**
     * 为用户创建一个初始余额为0的钱包。
     *
     * @param userId 用户ID
     */
    @Override
    public int createWallet(String userId) {
        Wallet wallet = new Wallet(userId, 0.0, 0.0, 0.0, 0.0);
        return walletMapper.createWallet(wallet);
    }

    public boolean pay(Integer oderId){
        Orders order = ordersMapper.getOrdersById(oderId);
        int businessid = order.getBusinessId();
        Business business = businessMapper.getBusinessById(businessid);
        String touserId = business.getOwnerUserId();
        String fromuserId = order.getUserId();
        double amount = order.getOrderTotal()/2;
        boolean res = transfer(fromuserId, touserId, amount);
        if(res) {
            order.setOrderState(1);
            ordersMapper.updateOrdersState(order);
            order.setOrderState(0);
            ordersMapper.saveAcceptableOrders(order);
        }
        return res;
    }
}